package com.jianan.mis.app.overseastudy;

import static com.jianan.mis.util.ui.table.TableCreator.createTableColumn;

import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import org.eclipse.jface.dialogs.Dialog;
import org.eclipse.jface.dialogs.IDialogConstants;
import org.eclipse.jface.dialogs.IInputValidator;
import org.eclipse.jface.dialogs.InputDialog;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jface.viewers.IStructuredContentProvider;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.jface.viewers.ITableLabelProvider;
import org.eclipse.jface.viewers.LabelProvider;
import org.eclipse.jface.viewers.TableViewer;
import org.eclipse.jface.viewers.Viewer;
import org.eclipse.jface.window.Window;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.graphics.Point;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Table;
import org.eclipse.swt.widgets.Text;

import com.jianan.mis.data.domain.OsContract;
import com.jianan.mis.data.domain.OsContractFinanceDetail;
import com.jianan.mis.service.OsContractService;
import com.jianan.mis.sys.IMessageKeys;
import com.jianan.mis.sys.ResourceManager;
import com.jianan.mis.sys.SpringBeanFactory;
import com.jianan.mis.util.CurrencyUtils;
import com.jianan.mis.util.StringUtils;

public class OsFinanceDialog extends Dialog {
	
	private OsContract osContract;
	
	private int mode = 0;
	
	private List<OsContractFinanceDetail> osContractFinanceDetails;
	
	private OsContractService osContractService;
	
	private boolean modified = false;

	class TableLabelProvider extends LabelProvider implements ITableLabelProvider {
		public String getColumnText(Object element, int columnIndex) {
			OsContractFinanceDetail osContractFinanceDetail = (OsContractFinanceDetail) element;
			String text = details.getColumn(columnIndex).getText();
			if (text.equals(DETAIL_DATE)) {
				return dateFormat.format(osContractFinanceDetail.getCreateDate());
			} else if (text.equals(DETAIL_SUM)) {
				return "￥" + osContractFinanceDetail.getSum().toString();
			} else if (text.equals(DETAIL_REASON)) {
				return osContractFinanceDetail.getReason();
			} else {
				return null;
			}
		}
		public Image getColumnImage(Object element, int columnIndex) {
			return null;
		}
	}
	class ContentProvider implements IStructuredContentProvider {
		public Object[] getElements(Object inputElement) {
			return ((List) inputElement).toArray();
		}
		public void dispose() {
		}
		public void inputChanged(Viewer viewer, Object oldInput, Object newInput) {
		}
	}
	private BigDecimal commuTranslateSum;
	private BigDecimal sum;
	private Text txtBalance;
	private Label lblBalance;
	private Text txtCommuTranslateSum;
	private Label lblCommuTranslateSum;
	private Text txtSum;
	private Label lblSum;
	
	private TableViewer detailTableViewer;
	private Table details;
	
	final private SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy年MM月dd日");
	
	/**
	 * Create the dialog
	 * @param parentShell
	 */
	public OsFinanceDialog(Shell parentShell) {
		super(parentShell);
	}

	/**
	 * Create contents of the dialog
	 * @param parent
	 */
	@Override
	protected Control createDialogArea(Composite parent) {
		Composite container = (Composite) super.createDialogArea(parent);
		final GridLayout gridLayout = new GridLayout();
		gridLayout.marginWidth = 15;
		gridLayout.marginHeight = 15;
		gridLayout.numColumns = 3;
		container.setLayout(gridLayout);

		final Label label = new Label(container, SWT.NONE);
		label.setLayoutData(new GridData());
		label.setFont(ResourceManager.getFont("", 10, SWT.BOLD));
		label.setText("签约金额:");

		txtSum = new Text(container, SWT.BORDER);
		txtSum.setEditable(false);
		final GridData gd_txtSum = new GridData(150, SWT.DEFAULT);
		txtSum.setLayoutData(gd_txtSum);

		lblSum = new Label(container, SWT.NONE);
		final GridData gd_lblSum = new GridData(SWT.FILL, SWT.CENTER, false, false);
		lblSum.setLayoutData(gd_lblSum);

		final Label label_3 = new Label(container, SWT.NONE);
		label_3.setLayoutData(new GridData());
		label_3.setFont(ResourceManager.getFont("", 10, SWT.BOLD));
		label_3.setText("通讯翻译费:");

		txtCommuTranslateSum = new Text(container, SWT.BORDER);
		txtCommuTranslateSum.setEditable(false);
		final GridData gd_txtCommuTranslateSum = new GridData(150, SWT.DEFAULT);
		txtCommuTranslateSum.setLayoutData(gd_txtCommuTranslateSum);

		lblCommuTranslateSum = new Label(container, SWT.NONE);
		final GridData gd_lblCommuTranslateSum = new GridData(SWT.FILL, SWT.CENTER, false, false);
		lblCommuTranslateSum.setLayoutData(gd_lblCommuTranslateSum);

		new Label(container, SWT.NONE);
		new Label(container, SWT.NONE);
		new Label(container, SWT.NONE);

		final Label label_1 = new Label(container, SWT.NONE);
		label_1.setLayoutData(new GridData());
		label_1.setFont(ResourceManager.getFont("", 10, SWT.BOLD));
		label_1.setText("财务明细:");
		new Label(container, SWT.NONE);

		detailTableViewer = new TableViewer(container, SWT.FULL_SELECTION | SWT.BORDER);
		detailTableViewer.setLabelProvider(new TableLabelProvider());
		detailTableViewer.setContentProvider(new ContentProvider());
		details = detailTableViewer.getTable();
		details.setLinesVisible(true);
		details.setHeaderVisible(true);
		final GridData gd_table = new GridData(SWT.FILL, SWT.FILL, true, true, 3, 1);
		gd_table.heightHint = 150;
		details.setLayoutData(gd_table);

		final Button btnAddDetail = new Button(container, SWT.NONE);
		btnAddDetail.addSelectionListener(new SelectionAdapter() {
			public void widgetSelected(final SelectionEvent e) {
				InputDialog dateDialog = new InputDialog(getShell(), "添加财务明细",
						"请输入明细日期:", dateFormat.format(new Date()), new IInputValidator() {
							public String isValid(String newText) {
								if (StringUtils.isEmpty(newText)) {
									return "日期不得为空!";
								}
								try {
									dateFormat.parse(newText);
								} catch (ParseException ex) {
									ex.printStackTrace();
									return "输入日期格式不正确(正确格式:yyyy年MM月dd日)";
								}
								return null;
							}
						});
				if(dateDialog.open() != Window.OK)
					return;
				InputDialog sumDialog = new InputDialog(getShell(), "添加财务明细",
						"请输入明细金额(元):", "0.00", new IInputValidator() {
							public String isValid(String newText) {
								if (StringUtils.isEmpty(newText)) {
									return "金额不得为空!";
								}
								try {
									new BigDecimal(newText)
											.setScale(2, BigDecimal.ROUND_HALF_UP);
								} catch (Exception ex) {
									ex.printStackTrace();
									return "金额输入不正确!";
								}
								return null;
							}
						});
				if(sumDialog.open() != Window.OK)
					return;
				InputDialog reasonDialog = new InputDialog(getShell(), "添加财务明细",
						"请输入明细理由:", "", new IInputValidator() {
							public String isValid(String newText) {
								if (StringUtils.isEmpty(newText)) {
									return "理由不得为空!";
								}
								return null;
							}
						});
				if(reasonDialog.open() != Window.OK)
					return;
				
				modified = true;
				OsContractFinanceDetail detail = new OsContractFinanceDetail();
				detail.setOsContract(osContract);
				try {
					detail.setCreateDate(dateFormat.parse(dateDialog.getValue()));
				} catch (ParseException ex) {
					ex.printStackTrace();
					detail.setCreateDate(null);
				}
				detail.setSum(new BigDecimal(sumDialog.getValue()).setScale(2, BigDecimal.ROUND_HALF_UP));
				detail.setReason(reasonDialog.getValue());
				osContractFinanceDetails.add(detail);
				detailTableViewer.refresh();
				computeBalance();
			}
		});
		btnAddDetail.setLayoutData(new GridData(SWT.CENTER, SWT.CENTER, false, false, 2, 1));
		btnAddDetail.setText("添加明细");

		final Button btnDelDetail = new Button(container, SWT.NONE);
		btnDelDetail.addSelectionListener(new SelectionAdapter() {
			public void widgetSelected(final SelectionEvent e) {
				IStructuredSelection selection = (IStructuredSelection) detailTableViewer
						.getSelection();
				OsContractFinanceDetail detail = (OsContractFinanceDetail) selection
						.getFirstElement();
				if (detail == null) {
					MessageDialog.openInformation(e.display.getActiveShell(),
							IMessageKeys.FAIL, "请先选择一条明细!");
				} else {
					if (MessageDialog.openConfirm(e.display.getActiveShell(),
							IMessageKeys.CONFIRM, "确认删除该条明细吗?")) {
						modified = true;
						osContractFinanceDetails.remove(details.getSelectionIndex());
						detailTableViewer.refresh();
						computeBalance();
					}
				}
			}
		});
		btnDelDetail.setLayoutData(new GridData(SWT.CENTER, SWT.CENTER, false, false));
		btnDelDetail.setText("删除明细");

		new Label(container, SWT.NONE);
		new Label(container, SWT.NONE);
		new Label(container, SWT.NONE);

		final Label label_2 = new Label(container, SWT.NONE);
		label_2.setFont(ResourceManager.getFont("", 10, SWT.BOLD));
		label_2.setLayoutData(new GridData());
		label_2.setText("余额:");

		txtBalance = new Text(container, SWT.BORDER);
		txtBalance.setEditable(false);
		final GridData gd_txtBalance = new GridData(150, SWT.DEFAULT);
		txtBalance.setLayoutData(gd_txtBalance);

		lblBalance = new Label(container, SWT.NONE);
		lblBalance.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, false, false));
		
		initializeServices();
		initializeTableViewer();
		fillData();
		
		if (mode == 0) {
			btnAddDetail.setEnabled(true);
			btnDelDetail.setEnabled(true);
		} else {
			btnAddDetail.setEnabled(false);
			btnDelDetail.setEnabled(false);
		}
		
		//
		return container;
	}
	
	public static final String DETAIL_DATE = "日期";
	public static final String DETAIL_SUM = "金额(单位:元)";
	public static final String DETAIL_REASON = "理由";
	
	private void initializeTableViewer() {
		createTableColumn(detailTableViewer, SWT.CENTER, DETAIL_DATE, "", 120, null);
		createTableColumn(detailTableViewer, SWT.CENTER, DETAIL_SUM, "", 100, null);
		createTableColumn(detailTableViewer, SWT.CENTER, DETAIL_REASON, "", 220, null);
	}
	
	public void setMode(int mode) {
		this.mode = mode;
	}

	public void setOsContract(OsContract osContract) {
		this.osContract = osContract;
	}
	
	private void initializeServices() {
		osContractService = (OsContractService) SpringBeanFactory.getBean("osContractService");
	}
	
	private void fillData() {
		sum = osContract.getSignupSum().setScale(2, BigDecimal.ROUND_HALF_UP);
		txtSum.setText("￥" + sum.toString());
		lblSum.setText(CurrencyUtils.numberCurrencyToChineseCurrency(sum));

		if (osContract.getCommuTranslateSum() != null) {
			commuTranslateSum = osContract.getCommuTranslateSum().setScale(2, BigDecimal.ROUND_HALF_UP);
			txtCommuTranslateSum.setText("￥" + commuTranslateSum.toString());
			lblCommuTranslateSum.setText(CurrencyUtils.numberCurrencyToChineseCurrency(commuTranslateSum));
		} else {
			commuTranslateSum = BigDecimal.ZERO;
			txtCommuTranslateSum.setText("");
			lblCommuTranslateSum.setText("");
		}
		
		osContractFinanceDetails = osContractService.getFinanceDetails(osContract);
		detailTableViewer.setInput(osContractFinanceDetails);
		
		computeBalance();
	}
	
	private void computeBalance() {
		BigDecimal balance = sum.add(commuTranslateSum);
		for(OsContractFinanceDetail detail : osContractFinanceDetails) {
			balance = balance.add(detail.getSum().setScale(2, BigDecimal.ROUND_HALF_UP));
		}
		txtBalance.setText("￥" + balance.toString());
		lblBalance.setText(CurrencyUtils.numberCurrencyToChineseCurrency(balance));
	}

	/**
	 * Create contents of the button bar
	 * @param parent
	 */
	@Override
	protected void createButtonsForButtonBar(Composite parent) {
		if (mode == 0) {
			createButton(parent, IDialogConstants.OK_ID, "保存",
					true);
			createButton(parent, IDialogConstants.CANCEL_ID,
					IDialogConstants.CANCEL_LABEL, false);
		} else {
			createButton(parent, IDialogConstants.CANCEL_ID,
					IDialogConstants.OK_LABEL, false);
		}
	}

	/**
	 * Return the initial size of the dialog
	 */
	@Override
	protected Point getInitialSize() {
		return new Point(500, 449);
	}
	protected void configureShell(Shell newShell) {
		super.configureShell(newShell);
		newShell.setText("留学签约财务明细");
	}
	protected void buttonPressed(int buttonId) {
		if (buttonId == IDialogConstants.OK_ID) {
			if (modified) {
				try {
					osContractService.updateFinanceDetails(osContract,
							osContractFinanceDetails);
					MessageDialog.openInformation(getShell(),
							IMessageKeys.SUCCESS, "留学签约财务明细保存成功!");
				} catch (Exception ex) {
					MessageDialog.openError(getShell(), IMessageKeys.FAIL, ex
							.getMessage());
				}	
			}
		}
		super.buttonPressed(buttonId);
	}

}
